<template>
  <div class="container mx-auto px-4 my-4">
    <h1 class="text-2xl font-bold text-gray-800 mb-6">{{ t('仪表盘') }}</h1>

    <!-- 状态统计卡片 -->
    <div class="grid grid-cols-2 gap-6 mb-6">
      <div v-for="item in statusData" :key="item.key"
           class="p-8 flex justify-between bg-gradient-to-r from-indigo-500 to-purple-600 text-2xl text-white rounded-lg shadow-lg hover:shadow-xl transition-shadow duration-300">
        <span>{{ item.label }}</span>
        <span class="font-bold">{{ item.value }}</span>
      </div>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
      <!-- 月度统计折线图 -->
      <div class="bg-white p-6 rounded-lg shadow">
        <h2 class="text-lg font-semibold text-gray-800 mb-4">{{ t('月度电池护照生成统计') }}</h2>
        <div class="h-80">
          <LineChart v-if="monthlyData.datasets[0].data.length > 0"
                     :data="monthlyData" :options="lineOptions" />
          <div v-else class="h-full flex items-center justify-center text-gray-500">
            {{ t('暂无数据') }}
          </div>
        </div>
      </div>

      <!-- 年度统计折线图 -->
      <div class="bg-white p-6 rounded-lg shadow">
        <h2 class="text-lg font-semibold text-gray-800 mb-4">{{ t('电池制造年份分布') }}</h2>
        <div class="h-80">
          <LineChart v-if="yearlyData.datasets[0].data.length > 0"
                     :data="yearlyData" :options="lineOptions" />
          <div v-else class="h-full flex items-center justify-center text-gray-500">
            {{ t('暂无数据') }}
          </div>
        </div>
      </div>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
      <!-- 电池型号饼图 -->
      <div class="bg-white p-6 rounded-lg shadow">
        <h2 class="text-lg font-semibold text-gray-800 mb-4">{{ t('电池型号分布') }}</h2>
        <div class="h-80">
          <PieChart v-if="modelData.datasets[0].data.length > 0"
                    :data="modelData" :options="pieOptions" />
          <div v-else class="h-full flex items-center justify-center text-gray-500">
            {{ t('暂无数据') }}
          </div>
        </div>
      </div>

      <!-- 电池制造商饼图 -->
      <div class="bg-white p-6 rounded-lg shadow">
        <h2 class="text-lg font-semibold text-gray-800 mb-4">{{ t('电池制造商分布') }}</h2>
        <div class="h-80">
          <PieChart v-if="manufacturerData.datasets[0].data.length > 0"
                    :data="manufacturerData" :options="pieOptions" />
          <div v-else class="h-full flex items-center justify-center text-gray-500">
            {{ t('暂无数据') }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {onMounted, ref} from 'vue'
import {
  ArcElement,
  CategoryScale,
  Chart as ChartJS,
  Legend,
  LinearScale,
  LineElement,
  PointElement,
  Title,
  Tooltip
} from 'chart.js'
import {Line as LineChart, Pie as PieChart} from 'vue-chartjs'
import batteryPassportApi from "@/api/batteryPassport.js";
import {ElMessage} from "element-plus";
import {useI18n} from "vue-i18n";

const {t} = useI18n()

// 注册Chart.js组件
ChartJS.register(
    ArcElement, Tooltip, Legend,
    CategoryScale, LinearScale,
    PointElement, LineElement, Title
)

// 响应式数据
const statusData = ref([
  {label: t("已生成电池护照"), key: "PUBLISHED", value: 0},
  {label: t("创建中的电池护照"), key: "DRAFT", value: 0},
])

// 月度数据 - 初始化为空
const monthlyData = ref({
  labels: [],
  datasets: [
    {
      label: t('电池护照生成数量'),
      backgroundColor: '#4F46E5',
      borderColor: '#4F46E5',
      data: [],
      tension: 0.1,
      fill: false
    }
  ]
})

// 年度数据 - 初始化为空
const yearlyData = ref({
  labels: [],
  datasets: [
    {
      label: t('电池护照数量'),
      backgroundColor: '#10B981',
      borderColor: '#10B981',
      data: [],
      tension: 0.1,
      fill: false
    }
  ]
})

// 电池型号数据 - 初始化为空
const modelData = ref({
  labels: [],
  datasets: [
    {
      backgroundColor: ['#3B82F6', '#EF4444', '#10B981', '#F59E0B', '#8B5CF6', '#6B7280'],
      data: []
    }
  ]
})

// 电池制造商数据 - 初始化为空
const manufacturerData = ref({
  labels: [],
  datasets: [
    {
      backgroundColor: ['#3B82F6', '#EF4444', '#10B981', '#F59E0B', '#8B5CF6', '#6B7280', '#EC4899', '#84CC16'],
      data: []
    }
  ]
})

// 图表配置
const lineOptions = ref({
  responsive: true,
  maintainAspectRatio: false,
  plugins: {
    legend: {
      position: 'top',
    },
    tooltip: {
      mode: 'index',
      intersect: false,
    }
  },
  scales: {
    y: {
      beginAtZero: true,
      ticks: {
        precision: 0
      }
    }
  }
})

const pieOptions = ref({
  responsive: true,
  maintainAspectRatio: false,
  plugins: {
    legend: {
      position: 'right',
    },
    tooltip: {
      callbacks: {
        label: function(context) {
          const label = context.label || '';
          const value = context.raw || 0;
          const total = context.dataset.data.reduce((a, b) => a + b, 0);
          const percentage = Math.round((value / total) * 100);
          return `${label}: ${value} (${percentage}%)`;
        }
      }
    }
  }
})

// 数据初始化
const init = async () => {
  try {
    await Promise.all([
      loadStatusData(),
      loadMonthlyData(),
      loadYearlyData(),
      loadModelData(),
      loadManufacturerData()
    ])
  } catch (error) {
    ElMessage.error(t('数据加载失败'))
    console.error('初始化数据失败:', error)
  }
}

// 加载状态数据
const loadStatusData = async () => {
  const res = await batteryPassportApi.countByPublishStatus()
  if (res.code === 200) {
    statusData.value.forEach(item => {
      item.value = res.data.find(stat => stat.name === item.key)?.count || 0;
    })
  } else {
    ElMessage.error(res.message)
  }
}

// 加载月度数据
const loadMonthlyData = async () => {
  const res = await batteryPassportApi.countByMonth()
  if (res.code === 200 && res.data.length > 0) {
    monthlyData.value.labels = res.data.map(item => item.name)
    monthlyData.value.datasets[0].data = res.data.map(item => item.count)
  }
}

// 加载年度数据
const loadYearlyData = async () => {
  const res = await batteryPassportApi.countByYear()
  if (res.code === 200 && res.data.length > 0) {
    yearlyData.value.labels = res.data.map(item => item.name)
    yearlyData.value.datasets[0].data = res.data.map(item => item.count)
  }
}

// 加载型号数据
const loadModelData = async () => {
  const res = await batteryPassportApi.countByModel()
  if (res.code === 200 && res.data.length > 0) {
    // 翻译电池型号
    const modelTranslations = {
      'lmt': t('轻型交通工具'),
      'ev': t('电动汽车'),
      'industrial': t('工业用'),
      'stationary': t('固定式')
    }

    modelData.value.labels = res.data.map(item => modelTranslations[item.name] || item.name)
    modelData.value.datasets[0].data = res.data.map(item => item.count)
  }
}

// 加载制造商数据
const loadManufacturerData = async () => {
  const res = await batteryPassportApi.countByManufacturer()
  if (res.code === 200 && res.data.length > 0) {
    // 只显示前8个制造商，其他的归为"其他"
    const topManufacturers = res.data.slice(0, 8)
    const othersCount = res.data.slice(8).reduce((sum, item) => sum + item.count, 0)

    manufacturerData.value.labels = topManufacturers.map(item => item.name)
    manufacturerData.value.datasets[0].data = topManufacturers.map(item => item.count)

    if (othersCount > 0) {
      manufacturerData.value.labels.push(t('其他'))
      manufacturerData.value.datasets[0].data.push(othersCount)
    }
  }
}

onMounted(() => {
  init()
})
</script>